import pickle
import numpy as np
import pandas as pd
import os, glob
import seaborn as sns
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedKFold, cross_validate
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
## The following are the ML models which can be used for trasinning
from sklearn.model_selection import RandomizedSearchCV
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import MinMaxScaler,StandardScaler
import timeit
import warnings
warnings.filterwarnings("ignore")
E:\Anaconda3\envs\tf\lib\site-packages\xgboost\compat.py:36: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead. from pandas import MultiIndex, Int64Index
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
%matplotlib inline
import pandas as pd
import seaborn as sns
sns.set(style="darkgrid")
sns.set_context('talk')
from IPython.display import display, HTML, Image
import matplotlib.colors as mcolors
dataFolder = os.getcwd()
modelParentFolder = os.path.dirname(dataFolder)
group1_low =1.634
group2_low =0.673
group2_upper =1.634
group3_upper =0.673
## read the test file
data =pd.read_csv(os.path.join(dataFolder,'dataset5K_train.csv'))
data.columns =[col.strip() for col in data.columns]
data['ratio'] = data['b(CaO)']/data['b(SiO2)']
group1 = data[data['ratio']>=group1_low] # with Portlandite, no Amor-S1
group2 = data[(data['ratio']<=group2_upper) & (data['ratio']>=group2_low)] # no Portlandite, no Amor-S1
group3 = data[data['ratio']<=group3_upper] # no Portlandite, with Amor-S1
groups = [group1,group2,group3]
dataCols = data.columns
modelSummary={'rfModel':'ModelTrainSummary_rfModel.csv',
'lgbModel':'ModelTrainSummary_lgBoost.csv',
'gbModel':'ModelTrainSummary_gBoost.csv',
'GPyModel':'ModelTrainSummary_GPy.csv'
}
## read trained Model info:
def getReadyModelInfo(dataFolder,fileNameModelSummary,dataCols):
modelInfo =pd.read_csv(os.path.join(dataFolder,fileNameModelSummary))
modelInfo = modelInfo.iloc[:,1:4]
## load the mdoels
dataCols = data.columns.to_list()
modelsLst = []
for irow,row in modelInfo.iterrows():
group = row['group']
var =row['var']
modelType = row['modelType']
icol =dataCols.index(var)
if '/' in var:
fileCol = var.replace("/",'')
else:
fileCol = var
modelFolder = os.path.join(dataFolder,'SavedModel',group)
if modelType=='CONST':
ext = '.csv'
fileName = os.path.join(modelFolder,modelType + '_'+str(icol)+'_'+fileCol+ext)
tempModel =pd.read_csv(fileName)
else:
ext ='.sav'
fileName = os.path.join(modelFolder,modelType + '_'+str(icol)+'_'+fileCol+ext)
tempModel = pickle.load(open(fileName, 'rb'))
modelsLst.append(tempModel)
modelInfo['modelObj'] = modelsLst
return modelInfo
finalDF = pd.DataFrame()
for ML,modelSummaryCsv in modelSummary.items():
tempModelInfo = getReadyModelInfo(modelParentFolder,modelSummaryCsv,dataCols)
for col in group1.columns[4:-1]: # exclude 'ratio'
colModelInfo = tempModelInfo[tempModelInfo['var'] == col]
for i, group in enumerate(groups):
dataX = group.iloc[:,1:4]
dataY = group[col].values
groupModelInfo = colModelInfo[colModelInfo['group'] =='group'+str(i+1)]
modelType = groupModelInfo['modelType'].values[0]
model = groupModelInfo['modelObj'].values[0]
if modelType=='CONST':
y_pred = list(model['const'].values)*len(dataY)
elif modelType=='linear':
y_pred = model.predict(dataX.values)
else:
scaler = StandardScaler().fit(dataX.values)
X_scaled = scaler.transform(dataX.values) # This will be used for input of trainning dataset
y_pred = model.predict(X_scaled)
tempDF = pd.DataFrame({'testDataY':dataY, 'predDataY':y_pred})
tempDF['modelType'] = [modelType]*len(tempDF)
tempDF['var'] = [col]*len(tempDF)
tempDF['group'] = ['group'+str(i+1)]*len(tempDF)
tempDF['modelSimulation'] = [ML+'_simulation']*len(tempDF)
if len(finalDF)==0:
finalDF = tempDF
else:
finalDF = pd.concat([finalDF,tempDF],axis=0)
finalDF.to_csv('Comparison_predict_5KTrainDataset.csv',index=False)
def drawPlots(trgVar,testDataY,predDataY,simulation):
fig, ax =plt.subplots(figsize=(8,8))
RMSE = mean_squared_error(testDataY,predDataY)
R2 = r2_score(testDataY,predDataY)
axMax = max(max(testDataY),max(predDataY))
axMin = min(min(testDataY),min(predDataY))
## Fitting the line
x2= np.linspace(axMin,axMax,30);
y2 = x2
ax.plot(testDataY,predDataY,'bo',markerfacecolor = 'blue',markeredgecolor ='darkblue',markeredgewidth=0.5,label=trgVar)
#ax.plot(df3['b(SiO2)'].values,df3['b(CaO)'].values,'bo',markerfacecolor = 'c',markeredgecolor ='b',markeredgewidth=0.5,label='no Amor-S1')
#ax.plot(group3['b(SiO2)'].values,group3['b(CaO)'].values,'g^',markerfacecolor = 'm',markeredgecolor ='m',markeredgewidth=1,label='group3')
ax.plot(x2,y2,'r-',lw=3,label ='1:1 ratio')
ax.legend (loc='best',ncol=5)
ax.set_xlim(axMin,axMax)
ax.set_ylim(axMin,axMax)
#ax.text(0.05, 0.8, 'Above the line with Portlandite',fontsize = 20,color = 'k')
#ax.text(0.4, 0.50, 'Below the line no Portlandite',fontsize = 20,color = 'k')
ax.set_title(simulation+ ' ====> '+trgVar)
ax.set_xlabel('testDataY')
ax.set_ylabel('PredDataY')
return R2, RMSE
modelSimulations = finalDF['modelSimulation'].unique()
trgVars = finalDF['var'].unique()
statMeasure = []
for simulation in modelSimulations:
if 'MLP' in simulation or 'xgb' in simulation: # skip the xgb and MLP models
continue
tempDF = finalDF[finalDF['modelSimulation']==simulation]
for trgVar in trgVars:
df = tempDF[tempDF['var']==trgVar] # no Portlandite
testDataY = df['testDataY'].values
predDataY = df['predDataY'].values
R2,RMSE = drawPlots(trgVar,testDataY,predDataY,simulation)
statMeasure.append([trgVar,R2,RMSE,simulation])
statMeasDF = pd.DataFrame(statMeasure,columns=['Var','R2','RMSE','modelSimulation'])
statMeasDF
| Var | R2 | RMSE | modelSimulation | |
|---|---|---|---|---|
| 0 | Vol(aq) | 0.999427 | 5.419840e-07 | rfModel_simulation |
| 1 | pH | 0.998735 | 9.945622e-04 | rfModel_simulation |
| 2 | nCa(aq) | 0.997240 | 1.495189e-09 | rfModel_simulation |
| 3 | nCa(s) | 1.000000 | 1.463249e-08 | rfModel_simulation |
| 4 | nSi(aq) | 0.996122 | 5.867420e-11 | rfModel_simulation |
| 5 | nSi(s_reac) | 1.000000 | 2.740210e-10 | rfModel_simulation |
| 6 | nPortlandite | 0.999733 | 3.952987e-05 | rfModel_simulation |
| 7 | nAmor-Sl | 0.997959 | 1.048486e-05 | rfModel_simulation |
| 8 | mCSHQ | 0.999890 | 9.823665e-08 | rfModel_simulation |
| 9 | nCa(CSHQ) | 1.000000 | 1.726305e-08 | rfModel_simulation |
| 10 | nSi(CSHQ) | 1.000000 | 2.740210e-10 | rfModel_simulation |
| 11 | nH2O(CSHQ) | 0.999870 | 2.439941e-05 | rfModel_simulation |
| 12 | C/S(CSHQ) | 0.999292 | 9.079689e-05 | rfModel_simulation |
| 13 | nGelPW(CSH) | 0.999090 | 3.371381e-05 | rfModel_simulation |
| 14 | Vol(aq) | 0.999566 | 4.109325e-07 | lgbModel_simulation |
| 15 | pH | 0.998068 | 1.518691e-03 | lgbModel_simulation |
| 16 | nCa(aq) | 0.998203 | 9.734768e-10 | lgbModel_simulation |
| 17 | nCa(s) | 1.000000 | 1.463249e-08 | lgbModel_simulation |
| 18 | nSi(aq) | 0.995787 | 6.374570e-11 | lgbModel_simulation |
| 19 | nSi(s_reac) | 1.000000 | 2.740210e-10 | lgbModel_simulation |
| 20 | nPortlandite | 0.999651 | 5.153069e-05 | lgbModel_simulation |
| 21 | nAmor-Sl | 0.997504 | 1.282321e-05 | lgbModel_simulation |
| 22 | mCSHQ | 0.999817 | 1.629399e-07 | lgbModel_simulation |
| 23 | nCa(CSHQ) | 1.000000 | 1.726305e-08 | lgbModel_simulation |
| 24 | nSi(CSHQ) | 1.000000 | 2.740210e-10 | lgbModel_simulation |
| 25 | nH2O(CSHQ) | 0.999809 | 3.599640e-05 | lgbModel_simulation |
| 26 | C/S(CSHQ) | 0.999134 | 1.109978e-04 | lgbModel_simulation |
| 27 | nGelPW(CSH) | 0.999090 | 3.371381e-05 | lgbModel_simulation |
| 28 | Vol(aq) | 0.999088 | 8.627020e-07 | gbModel_simulation |
| 29 | pH | 0.996323 | 2.889717e-03 | gbModel_simulation |
| 30 | nCa(aq) | 0.996667 | 1.805085e-09 | gbModel_simulation |
| 31 | nCa(s) | 1.000000 | 1.463249e-08 | gbModel_simulation |
| 32 | nSi(aq) | 0.989041 | 1.658108e-10 | gbModel_simulation |
| 33 | nSi(s_reac) | 1.000000 | 2.740210e-10 | gbModel_simulation |
| 34 | nPortlandite | 0.998874 | 1.663732e-04 | gbModel_simulation |
| 35 | nAmor-Sl | 0.995568 | 2.276711e-05 | gbModel_simulation |
| 36 | mCSHQ | 0.999744 | 2.282690e-07 | gbModel_simulation |
| 37 | nCa(CSHQ) | 1.000000 | 1.726305e-08 | gbModel_simulation |
| 38 | nSi(CSHQ) | 1.000000 | 2.740210e-10 | gbModel_simulation |
| 39 | nH2O(CSHQ) | 0.999697 | 5.711597e-05 | gbModel_simulation |
| 40 | C/S(CSHQ) | 0.998503 | 1.919887e-04 | gbModel_simulation |
| 41 | nGelPW(CSH) | 0.999090 | 3.371381e-05 | gbModel_simulation |
| 42 | Vol(aq) | 0.999872 | 1.207104e-07 | GPyModel_simulation |
| 43 | pH | 0.998060 | 1.524882e-03 | GPyModel_simulation |
| 44 | nCa(aq) | 0.999784 | 1.169845e-10 | GPyModel_simulation |
| 45 | nCa(s) | 1.000000 | 1.463249e-08 | GPyModel_simulation |
| 46 | nSi(aq) | 0.984785 | 2.301995e-10 | GPyModel_simulation |
| 47 | nSi(s_reac) | 1.000000 | 2.740210e-10 | GPyModel_simulation |
| 48 | nPortlandite | 0.999921 | 1.164419e-05 | GPyModel_simulation |
| 49 | nAmor-Sl | 0.999239 | 3.908446e-06 | GPyModel_simulation |
| 50 | mCSHQ | 0.999916 | 7.460336e-08 | GPyModel_simulation |
| 51 | nCa(CSHQ) | 1.000000 | 1.726305e-08 | GPyModel_simulation |
| 52 | nSi(CSHQ) | 1.000000 | 2.740210e-10 | GPyModel_simulation |
| 53 | nH2O(CSHQ) | 0.999914 | 1.621333e-05 | GPyModel_simulation |
| 54 | C/S(CSHQ) | 0.999894 | 1.358704e-05 | GPyModel_simulation |
| 55 | nGelPW(CSH) | 0.999090 | 3.371381e-05 | GPyModel_simulation |
statMeasDF_pivot=statMeasDF.pivot(index='Var',values=['R2','RMSE'],columns='modelSimulation')
statMeasDF.to_csv('statMeasure_trainDataset_noPivot.csv',index = False)
statMeasDF_pivot.to_csv('statMeasure_trainDataset_Pivot.csv')
## alternative way to draw figures
def drawCombiningPlots(plotDataDF,trgVar):
fig, ax =plt.subplots(figsize=(10,10))
marker = ['o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X']
colors = ['tab:blue','tab:orange','tab:gray','tab:olive','tab:cyan','tab:green']
## Fitting the line
axisMin=1000
axisMax =-1000
for i, col in enumerate(plotDataDF.columns[1:]):
testDataY = plotDataDF.iloc[:,0].values
predDataY = plotDataDF[col].values
axMax = max(max(testDataY),max(predDataY))
axMin = min(min(testDataY),min(predDataY))
axisMin = min(axisMin,axMin)
axisMax = max(axisMax,axMax)
ax.scatter(testDataY,predDataY,marker =marker[i],edgecolor =colors[i],label=col.replace('_simulation',''))
x2= np.linspace(axisMin,axisMax,30);
y2 = x2
ax.plot(x2,y2,'r-',lw=3,label ='1:1 ratio')
ax.legend (loc='best',ncol=3)
ax.set_xlim(axisMin,axisMax)
ax.set_ylim(axisMin,axisMax)
ax.set_title(trgVar)
ax.set_xlabel('testDataY')
ax.set_ylabel('PredDataY')
modelSimulations = finalDF['modelSimulation'].unique()
trgVars = finalDF['var'].unique()
for trgVar in trgVars:
tempdf = finalDF[finalDF['var']==trgVar] # no Portlandite
dataplot = {}
plotDataDF = pd.DataFrame()
for simulation in modelSimulations:
# skip the xgb and MLP models
# the two models are very bad, need to be fine tune
if 'MLP' in simulation or 'xgb' in simulation:
continue
df = tempdf[tempdf['modelSimulation']==simulation]
if len(plotDataDF)==0:
plotDataDF=df[['testDataY','predDataY']]
else:
plotDataDF = pd.concat([plotDataDF,df[['predDataY']]],axis=1)
plotDataDF.rename({'predDataY': simulation}, axis=1,inplace=True)
drawCombiningPlots(plotDataDF,trgVar)